<template>
    <div class="tableContainer">
        <el-form :inline="true"  class="demo-form-inline" @submit.native.prevent>
            <el-form-item label="">
                <el-input class="elInput" v-model="key" placeholder="输入用户名/手机号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="elBtn" type="primary" @click="selectUserData">查询</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" max-height="88%" border style="width: 100%" >
            <el-table-column type="index" min-width="3%" align="center"></el-table-column>
            <el-table-column prop="userName" label="用户名称" min-width="15%"  align="center" :show-overflow-tooltip="true"> </el-table-column>
            <el-table-column prop="sex" label="性别" min-width="5%"  align="center" :show-overflow-tooltip="true" :formatter="this.$common.sexFormat"></el-table-column>
            <el-table-column prop="phone" label="手机号"  min-width="15%" align="center" :show-overflow-tooltip="true"> </el-table-column>
            <el-table-column prop="email" label="邮箱"  min-width="15%" align="center" :show-overflow-tooltip="true"> </el-table-column>
            <el-table-column prop="orgName" label="所属单位" min-width="10%" align="center" :show-overflow-tooltip="true"> </el-table-column>
            <el-table-column prop="roleName" label="所属角色"  min-width="10%" align="center" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"  min-width="15%" align="center" :show-overflow-tooltip="true" :formatter="this.$common.dateFormat"> </el-table-column>
            <el-table-column prop="op" label="操作" min-width="20%" align="center">
                <template slot-scope="scope">
                    <el-button class="elBtn"  type="primary" size="mini" icon="edit"  @click="openDialog(scope.$index, scope.row,1)">修改</el-button>
                    <el-button size="mini" icon="delete" type="danger" @click="openDialog(scope.$index, scope.row,2)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background 
			layout="prev, pager, next, sizes, total, jumper"
			:page-sizes="pagesizes"
			:page-size="pagesize"
			:total="totalNum"
            @current-change="changePage"
            @size-change="sizeChange"
			>
		</el-pagination>

        <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible" width="30%" center @close="clearForm">
            <el-form ref="form" :model="form" :rules="rules">
                <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth" >
                    <el-input class="elInput" v-model="form.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" :label-width="formLabelWidth" prop="sex" >
                    <el-select class="elInput" v-model="form.sex" placeholder="请选择">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                    <el-input class="elInput" v-model="form.phone" autocomplete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                    <el-input class="elInput" v-model="form.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所属单位" prop="orgId" :label-width="formLabelWidth" >
                    <!-- <select-tree class="elInput"  :options="unitOptions" v-model="form.orgIds" :props="defaultProps" autocomplete="off"/> -->
                    <!-- <select-tree :options="unitOptions" :props="defaultProps" :multiple="true"  v-model="form.orgIds"></select-tree> -->
                    <select-tree v-model="form.orgId" :multiple="true" placeholder="请选择" :options="unitOptions" />
                </el-form-item>
                <el-form-item label="角色" :label-width="formLabelWidth" prop="roleId" >
                    <el-select class="elInput" multiple v-model="form.roleId" placeholder="请选择">
                        <el-option
                        v-for="item in roleOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="userStatus" active-color="#13ce66" inactive-color="#ccc"  inactive-text="无效" active-text="有效"></el-switch> 
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clearForm">取 消</el-button>
                <el-button class="elBtn" type="primary" @click="doModifyUser">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="提示" :visible.sync="centerDialogVisible" width="30%" center>
            <span>确定删除这条用户信息</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button class="elBtn" type="primary" @click="doDeleteUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
    

</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    data() {
        return {
            dialogFormVisible: false, // 控制修改对话框的显示隐藏
            centerDialogVisible:false, // 控制删除提示框的显示隐藏
            userId:"", // 存选择数据的用户id
            pagesizes:[1,15,20,25],
            pagesize:1,// 每页条数
            currpage: 1, // 当前页
            totalNum:0, // 总条数
            options:[ 
                {label:"男",value:2},
                {label:"女",value:1}
            ],
            roleOptions:[], // 角色数据
            unitOptions:[], // 单位数据
            key: '',// 查询参数
            tableData: [], // 页面数据
            form: { // 表单参数
                userName: '',
                sex: '',
                phone: '',
                email: '',
                roleId: [],
                orgId:["01"],
                status:""
            },
            rules:{ // 用户修改密码的验证规则
                userName: [
                    {validator:this.$common.emptyValidate, trigger: 'blur'}
                ],
                sex: [
                    {validator:this.$common.emptyValidate, trigger: 'blur'}
                ],
                roleId: [
                    {validator:this.$common.emptyValidate, trigger: 'blur'}
                ],
            },
            userStatus:true,
            formLabelWidth: '20%', // label宽度
            tipMsg:"",
            clientHeight:"" // 屏幕高度
      }
    },
    created(){
        // 获取屏幕高度
        this.clientHeight = this.$common.getClientHeight()
        this.pagesize = Math.ceil((this.clientHeight - 265)/55)
        this.pagesizes[0] = this.pagesize

        // 当页面初始化的时候，获取用户信息
        this.selectUserData()
        
        // 获取角色数据
        this.$common.getAllRoles(res => {
            this.roleOptions = res.data.data
        })
        // 获取单位数据
        this.$common.selectAllUnit(res => {
            this.unitOptions = this.$common.dataFormat(res.data.data)
        })

        this.defaultCheckedKeys = [0];
    },
    mounted () {
        // 此处初始化defaultCheckedKeys，没效果
        this.defaultCheckedKeys = [0];
    },
    methods:{
        // 控制对话框显示隐藏
        openDialog(index,row,type){
            // 获取id
            this.userId = row.id
            if(type == 1){
                
                this.$api.selectUserById({params:{id: this.userId}})
                .then(result=>{
                    if(result.data.success){
                        this.dialogFormVisible = true
                    }
                    if(result.data.data.roles && result.data.data){
                        result.data.data.roleId = []
                        result.data.data.orgId = []
                        result.data.data.roles.forEach(element => {
                            result.data.data.roleId.push(element.id)
                        })
                        result.data.data.organizations.forEach(element => {
                            result.data.data.orgId.push(element.id)
                        })
                    }
                    this.form = result.data.data
                    this.userStatus = (this.form.status == 1)?true:false
                })
            }else{
                this.centerDialogVisible = true
            }
        },
        // 查询用户数据
        selectUserData(){
            const params = {}
            params.page = this.currpage
            params.limit = this.pagesize
            params.key = this.key?this.key:null

            this.$api.getAllUserData(params)
            .then(result=>{
                
                var _this = this
                this.$common.filterLogin(result,_this,()=>{
                    if(result.data.success){
                        // 得到用户关联角色
                        result.data.data.list.forEach(element => {
                            element.roleId = []
                            element.roleName = []
                            element.orgName = []
                            if(element.roles){
                                element.roles.forEach(e => {
                                    element.roleId.push(e.id)
                                    element.roleName.push(e.name)
                                })
                                element.roleName = element.roleName.join(',')
                            }
                            if(element.organizations){
                                element.organizations.forEach(el => {
                                    element.orgName.push(el.name)
                                })
                                element.orgName = element.orgName.join(',')
                            }
                        });

                        _this.tableData = result.data.data.list
                        _this.totalNum = result.data.data.total
                    }
                })
                
            })
        },
        // 修改用户信息
        doModifyUser(){
            this.$refs['form'].validate((valid) => {
                if(valid){
                    this.form.status = this.userStatus?1:2
                    this.form.createTime = ""
                    this.form.roles = []
                    
                    this.$api.modifyUser(this.form)
                    .then(result=>{
                        this.successFun(result,1)
                    })
                }
            })
            
        },
        // 删除用户信息
        doDeleteUser(){
            this.$api.deleteUser({id: this.userId})
            .then(result=>{
                this.successFun(result,2)
            })
        },
        // 接口调用成功的方法
        successFun(result,type){
            var _this = this
            this.$common.filterLogin(result,_this,()=>{
                _this.tipMsg = result.data.message 
                _this.selectUserData()
                _this.clearForm(type)
                _this.form.roleId = []
                if(result.data.success){
                    _this.$message({center: true,message: _this.tipMsg?_this.tipMsg:"操作成功",type: 'success'});
                }else{
                    this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                }
            })
            
        },
        // 清空表单
        clearForm(type){
            this.centerDialogVisible = false
            this.dialogFormVisible = false
            // 清楚表单数据
            for(let item in this.form){
                this.form[item] = ""
            }
            this.form.roleId = []
            this.form.orgId=["01"]
        },
        // 分页--改变当前页
        changePage(index){
            this.currpage = index
            this.selectUserData()
        },
        // 分页--改变当前页显示条数
        sizeChange(page){
            this.pagesize = page
            this.selectUserData()
        }
    },
    components: {
      'select-tree': Treeselect
    }
}
</script>

<style lang="scss" scoped>
.tableContainer{
    height: 96%;
    padding: 10px;
    background: #FDFDFD;
    border-radius: 5px;
    .el-pagination.is-background{
        text-align: right;
        padding:10px 5px;
    }
    .el-table,.el-table th, .el-table tr{
        background: transparent !important;
    }
}
</style>